"use client";

import easyFetch from "@/client/api/easyfetch";
import { useToast } from "@/components/ui/use-toast";
import { useRouter } from "next/navigation";
import PostEditorForm, { PostEditorFormValues } from "@/components/post-editor-form";

export default function EditorArea() {
  const { toast } = useToast();
  const router = useRouter();

  const save = (values: PostEditorFormValues) =>
    (async () => {
      const result = await easyFetch.post<{ postId: string }>("/api/posts", { body: { ...values, contentType: "md" } });
      if (result.ok) {
        toast({ description: "Succeed!" });
        router.push(`/posts/${result.data.postId}`);
      } else {
        toast({ description: result.message });
      }
    })();

  return <PostEditorForm initValues={{ title: "", content: "", personal: false }} onSave={save} />;
}
